const express = require('express')
const app = express()
const superagent = require('superagent')
const cherrio = require('cheerio')
const Nightmare = require('nightmare')
const nightmare = Nightmare({
    show: true
})
const FakeUseragent = require('fake-useragent')
const fs = require('fs')
const cp = require('child_process')
const {
    getMusicFromSingerPage,
    getMusicInfo,
    getArtistList,
    getSingleSingerMusicList,
    getSinglePageMusicList
} = require('./tools')

app.listen(3001, () => {
    // cp.exec('start http://localhost:3001')
})

// 获取歌手列表信息
function getArtistInfo() {
    let url = 'http://www.51ape.com/artist/'
    let data
    superagent.get(url).set('User-Agent', FakeUseragent()).end(async (err, res2) => {
        if (err) {
            throw Error('err')
        }
        data = await getArtistList(res2.text)
        fs.writeFile(__dirname + '/artistInfo.json', JSON.stringify(data), error => {
            if (error) {
                throw new Error('写入文件失败')
            }
            console.log('歌手列表存储成功')
        })
    })
}

// 获取歌手歌曲列表信息

const {
    pinyin
} = require('pinyin-pro')

// 获取汉字的拼音首字母大写/英文大写首字母
function getFirstLetter(words) {
    if (words.length < 1) return
    if (/^[\u4e00-\u9fa5]{0,}$/.test(words)) {
        return pinyin(words, {
            pattern: 'initial',
            type: 'array'
        }).map(v => v[0].toUpperCase())
    }
    return words[0].toUpperCase()
}


// 读取歌手信息数据
let data = fs.readFileSync(__dirname + "/artistInfo.json", {
    encoding: 'UTF-8'
})
data = JSON.parse(data)

let musicInfo = {}

for (const key in data) {
    for (const singer in data[key]) {
        let s = data[key][singer]
        musicInfo[s.id] = {}
        if (s.hasHome) {
            // let str = 'http://www.51ape.com/adu/'
            // superagent.get(encodeURI(s.homePage)).set('User-Agent', FakeUseragent()).end(async (err, res2) => {
            //     if (err) {
            //         throw Error('err')
            //     }
            //     let data = await getSinglePageMusicList(res2.text, s.homePage)
            //     musicInfo[s.id].songsList = data
            // })
        } else {
            setTimeout(() => {
                superagent.get(encodeURI(s.songsListPage)).set('User-Agent', FakeUseragent()).end(async (err, res2) => {
                    if (err) {
                        throw Error('err')
                    }
                    let data = await getSingleSingerMusicList(res2.text)
                    musicInfo[s.id].songsList = data
                    console.log(s.id)
                })
            }, 2000)
        }
    }
}


app.get('/', (req, res) => {
    fs.writeFile(__dirname + '/songsListInfo.json', JSON.stringify(musicInfo), error => {
        if (error) {
            throw new Error('歌曲列表写入文件失败')
        }
        console.log('歌曲列表存储成功')
    })
    res.send(musicInfo)
})